package com.business.util;

import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by mengdexuan on 2017/1/15 17:52.
 */
public class ZkClient {

	private static org.slf4j.Logger log = LoggerFactory.getLogger(ZkClient.class);

	// 会话超时时间，设置为与系统默认时间一致
	private static final int SESSION_TIMEOUT = 1000*30;

	// key : 集群ID	val : 客户端连接
	private static Map<String,ZooKeeper> clusterMap = new HashMap<>();

	private static Watcher wh = new Watcher() {
		public void process(org.apache.zookeeper.WatchedEvent event){
//			System.out.println("事件 --> "+event.toString());
		}
	};


	// 初始化 ZooKeeper 实例
	public static ZooKeeper getZk(String clusterId, String connStr) throws IOException {
		ZooKeeper temp = clusterMap.get(clusterId);
		if (temp!=null)return temp;
		else {
			temp = new ZooKeeper(connStr, ZkClient.SESSION_TIMEOUT, ZkClient.wh);
			clusterMap.put(clusterId,temp);
			log.info("创建 ZK 连接，集群信息 --> "+connStr);
			return temp;
		}
	}


	public static ZooKeeper getZk(String clusterId){
		return clusterMap.get(clusterId);
	}


	public static void close(ZooKeeper zk) throws InterruptedException {
		zk.close();
	}

	public static void clearConn(){
		clusterMap.clear();
	}

	public static void close(){
		if (HelpMe.isNotNull(clusterMap)){
			Collection<ZooKeeper> zkCollection = clusterMap.values();
			for (ZooKeeper zk:zkCollection){
				try {
					close(zk);
				}catch (Exception e){
					log.error(zk.toString());
					log.error("闭关 zk 客户端失败！",e);
				}
			}
		}
	}

}
